/**
 * 类名：箱子实体业务类
 * 备注：负责箱子实体业务逻辑。
 * 作者：rankin
 * 日期：2016/03/4
 */
var Page = require('../models/page');
var Box = require('../models/boxes');
var Sim = require('../models/sim');
var UserBox = require('../models/UserBox');
var User = require('../models/User');
var Active = require('../models/active');
var Prize = require('../models/prize');
var Billing = require('../models/billing');
var Log = require('../models/log');

var mqttclient = require('../utils/mqttclient');

var fs = require('fs');
var async = require('async');
var _ = require('underscore');
var Promise = require('bluebird');

module.exports = {

    /**
     * 箱子管理列表页
     * @param req
     * @param res
     */
    list: function (req, res) {

        var userid = req.session.user._id;
        var data = {
            datas: [],
            pageCount: 0
        };
        var params;
        if (req.session.permissionMap[1021]) {
            params = {}
        } else {
            params = {'owner': userid}
        }

        Box.paginate(params, {page: req.query.num, limit: 10}).then(function (result) {
            data.datas = result.docs;
            data.pageCount = result.pages;
            return Promise.map(result.docs, function (box, index, length) {
                return Sim.find({'box_id': box.box_id}).exec().then(function (sims) {
                    if (sims.length > 0) {
                        box.sim = sims[0].sim;
                    }
                    return Promise.resolve();
                });
            });
        }).then(function () {
            res.render('box/box_list', data);
        }).error(function (err) {
            res.send({success: false, err: err});
        });


    },
    to_create: function (req, res) {
        new User().findAll(function (datas) {
            var buyerdatas = datas;
            new Sim().findAllSim(function (datas) {
                var simdatas = datas;
                res.render('box/box_create', {
                    buyerdatas: buyerdatas,
                    simdatas: simdatas
                });
            });
        });
    },
    do_create: function (req, res) {
        var sim = req.body.sim;//获取sim卡号
        var buyer = req.body.buyer;//获取购买人姓名
        var box_layout = req.body.boxlayout;//获取箱子布局
        var doorsnum = req.body.doorNum;//获取格子数
        var codelayout = req.body.code_layout;//获取贴码位置
        var tim = new Date().getTime();
        var boxid = "SB_" + tim;
        var doors = [];
        for (var i = 0; i < doorsnum; i++) {
            doors.push({
                index: i + 1,
                empty: true,
                password: "",
                opentime: "",
                owner: "",
                prize_id: null,
                discount_price: null
            });
        }
        if (buyer == 0) {
            var nBox = new Box({
                box_id: boxid,
                code_layout: codelayout,
                doors_num: doorsnum,
                box_layout: box_layout,
                doors: doors,
                limit: true
            });
            nBox.save(function (err) {
                if (err) {
                    console.log(err);
                } else {
                    console.log("OK!");
                }
            });
            new Sim().updateIdBySim(sim, boxid, function (err) {
            });
        } else {
            var nBox = new Box({
                box_id: boxid,
                code_layout: codelayout,
                doors_num: doorsnum,
                box_layout: box_layout,
                doors: doors,
                owner: buyer,
                limit: true
            });

            nBox.save(function (err) {
                if (err) {
                    console.log(err);
                } else {
                    console.log("OK!");
                }
            });
            new Sim().updateIdBySim(sim, boxid, function (err) {
            });
        }
        new Log({
            box_id: boxid,
            user: "管理员", //操作人
            date: new Date(), //操作日期
            operation: "自定义生成箱子(格子数为:" + doorsnum + ")" //操作内容
        }).save();
        req.flash('success', '箱子已经生成.');
        return res.redirect('/box/list?num=1');
    },
    prize_list: function (req, res) {
        var boxid = req.query.boxid;
        var arr = [];
        new Box().findBoxById(boxid, function (data) {
            var count = 0;
            var datas = data[0].doors;
            async.whilst(function () {
                return count < datas.length;
            }, function (callback) {
                var door = {};
                if (datas[count].prize_id) {
                    new Prize().findPrizeById(datas[count].prize_id, function (result) {
                        door.index = datas[count].index;
                        door.price = result[0].price;
                        door.imgurl = result[0].imgurl;
                        door.name = result[0].name;
                        door.prize_id = datas[count].prize_id;
                        door.taobao_url = result[0].taobao_url;
                        door.discount_price = datas[count].discount_price;
                        arr.push(door);
                        count++;
                        callback();
                    });
                } else {
                    door.index = datas[count].index;
                    door.discount_price = datas[count].discount_price;
                    door.prize_id = null;
                    arr.push(door);
                    count++;
                    callback();
                }
            }, function (err) {
                res.render('box/box_prize_list', {datas: arr, boxid: boxid, box_layout: data[0].box_layout});
            });
        });
    },
    to_set: function (req, res) {
        var boxid = req.query.boxid;
        var index = req.query.index;
        new Prize().findAllPrize(function (err, datas) {
            res.render('box/box_prize_set', {datas: datas, boxid: boxid, index: index});
        });
    },
    do_set: function (req, res) {
        var boxid = req.body.boxid;
        var index = req.body.index;
        var prize = req.body.list;
        var discount_price = req.body.discount_price;
        new Box().updateBinding(boxid, index, prize, discount_price, function (boxid) {
            res.redirect('/box/prize/list?boxid=' + boxid);
        });
    },
    to_prize_edit: function (req, res) {
        var boxid = req.query.boxid;
        var index = req.query.index;
        new Box().findByBoxId(boxid, function (box) {
            var door = box.data[index - 1];
            console.log(door);
            new Prize().findAllPrize(function (err, datas) {
                var name = '';
                for (var i = 0; i < datas.length; i++) {
                    if (door.prize_id == datas[i]._id) {
                        name = datas[i].name;
                    }
                }
                res.render('box/box_prize_edit', {
                    datas: datas,
                    boxid: boxid,
                    index: index,
                    prize_id: door.prize_id,
                    discount_price: door.discount_price,
                    name: name
                });
            });
        });
    },
    reBinding: function (req, res) {
        var boxid = req.query.boxid;
        var index = req.query.index;
        new Box().updateReBinding(boxid, index, function (boxid) {
            res.redirect('/box/prize/list?boxid=' + boxid);
        });
    },
    rembox: function (req, res) {
        var boxid = req.query.boxid;
        new Box().removeById(boxid, function (err) {
            new UserBox().removeUserById(boxid, function (err) {
                new Sim().updateIdById(boxid, function (err) {
                    req.flash('success', '箱子已经删除.');
                    return res.redirect('/box/list?num=1');
                });
            });
        });
    },
    to_edit: function (req, res) {

        var boxid = req.query.boxid;
        var data = {
            buyerdatas: [],
            simdatas: [],
            boxid: boxid,
            buyer: '',
            sim: '',
            boxdatas: []
        };

        Box.find().where('box_id').equals(boxid).exec().then(function (boxes) {
            if (boxes.length == 0) {
                return res.send({success: false, err: 'the box do not exists.'});
            }
            data.boxdatas = boxes;
            return User.find().exec();
        }).then(function (users) {
            data.buyerdatas = users;
            return Sim.find().exec();
        }).then(function (sims) {
            data.simdatas = sims;
            return Sim.where('box_id').equals(boxid).exec();
        }).then(function (sims) {
            if (sims.length > 0)
                data.sim = sims[0].sim;
            res.render('box/box_edit', data);
        }).error(function (err) {
            res.send({success: false, err: err});
        });
    },
    do_edit: function (req, res) {
        var boxid = req.body.boxid;
        var sim = req.body.sim;
        var buyer = req.body.buyer;
        var code_layout = req.body.code_layout;
        var door_num = req.body.door_num;
        var box_layout = req.body.box_layout;
        var osim = req.body.osim;

        //修改用户名
        if (buyer == 0) {
            new UserBox().removeUserById(boxid, function (err) {
            });
        } else {
            Box.update({box_id: boxid}, {owner: buyer}).exec();
        }
        //修改Sim卡号
        if (sim == 0) {
            console.log("没有修改Sim卡");
        } else {
            var nboxid = "未绑定";
            new Sim().updateIdBySim(osim, nboxid, function (err) {
            });
            new Sim().updateIdBySim(sim, boxid, function (err) {
            });
        }
        //修改箱子信息
        if (code_layout == 0) {
            if (door_num == 0) {

            } else {
                var doors = [];
                for (var i = 0; i < door_num; i++) {
                    doors.push({
                        index: i + 1,
                        empty: true,
                        password: "",
                        opentime: "",
                        owner: ""
                    });
                }
                new Box().updateDoorNumById(boxid, doors, door_num, box_layout, function (err) {
                });
            }
        } else {
            if (door_num == 0) {
                new Box().updateCodeById(boxid, code_layout, function (err) {
                });
            } else {
                var doors = [];
                for (var i = 0; i < door_num; i++) {
                    doors.push({
                        index: i + 1,
                        empty: true,
                        password: "",
                        opentime: "",
                        owner: ""
                    });
                }
                new Box().updateAllById(boxid, doors, door_num, box_layout, code_layout, function (err) {
                });
            }
        }
        new Log({
            box_id: boxid,
            user: "管理员", //操作人
            date: new Date(), //操作日期
            operation: "箱子信息更新成功" //操作内容
        }).save();
        req.flash('success', '箱子信息更新成功.');
        res.redirect('/box/list?num=1');
    },
    box_order: function (req, res) {
        var boxid = req.query.boxid;
        new Box().findBoxById(boxid, function (datas) {
            var boxDatas = datas;
            new Sim().findSimById(boxid, function (datas) {
                var simDatas = datas;
                new UserBox().findUserById(boxid, function (datas) {
                    if (datas == null) {
                        var datas = 0;
                        res.render('box/box_order', {
                            simdatas: simDatas,
                            boxdatas: boxDatas,
                            buyerdatas: datas
                        });
                    } else {
                        var buyer_id = datas.buyer_id;
                        new User().findById(buyer_id, function (datas) {
                            var buyerdatas = datas;
                            res.render('box/box_order', {
                                simdatas: simDatas,
                                boxdatas: boxDatas,
                                buyerdatas: buyerdatas
                            });
                        });
                    }
                });
            });
        });
    },
    doors: function (req, res) {
        var boxid = req.query.boxid;
        var index = req.query.index;
        if (index == -1) {
            var doorsnum = req.query.doorsnum;
            var count = 0;
            async.whilst(function () {
                return count < doorsnum;
            }, function (callback) {
                new Box().updateByBoxidAndIndex(boxid, Number(count + 1), false, function (data) {//false是不为空状态
                    count++;
                    callback();
                });

            }, function (err) {
                new Box().findByBoxId(boxid, function (box) {
                    var list = box.data;
                    res.render("box/box_doors", {
                        "boxid": boxid,
                        "doordatas": list,
                        "limit": box.boxlimit
                    });
                });

                new Log({
                    box_id: boxid,
                    user: req.session.user.user, //操作人
                    date: new Date(), //操作日期
                    operation: "设置为充满物品状态。", //操作内容
                    opertype: "open"
                }).save();
            });

        } else if (index == 0) {
            new Box().findByBoxId(boxid, function (box) {
                var list = box.data;
                res.render("box/box_doors", {
                    "boxid": boxid,
                    "doordatas": list,
                    "limit": box.boxlimit
                });
            });
        } else if (index == "all") {
            var doorsnum = req.query.doorsnum;
            var doors = [];
            for (var i = 0; i < doorsnum; i++) {
                doors.push({
                    index: i + 1,
                    empty: false,//打开全部后直接设置为不空闲状态，用于填充奖品
                    password: "",
                    opentime: "",
                    owner: "",
                    prize_id: "",
                    discount_price: ""
                });
            }
            new Sim().findSimById(boxid, function (datas) {
                //client = mqtt.createClient(1883, '114.215.137.61');
                var sim = datas.sim;
                var j = 1;
                for (var i = 0; i < doorsnum; i++) {
                    mqttclient.publish(sim, 'open' + j);
                    j++;
                }
            });
            new Box().updateDoorById(boxid, doors, function () {
                new Box().findByBoxId(boxid, function (box) {
                    var list = box.data;
                    res.render("box/box_doors", {
                        "boxid": boxid,
                        "doordatas": list,
                        "limit": box.boxlimit
                    });
                });
            });
            new Log({
                box_id: boxid,
                user: req.session.user.user, //操作人
                date: new Date(), //操作日期
                operation: "打开箱子门:所有", //操作内容
                opertype: "open"
            }).save();
        } else {
            new Box().updateByBoxidAndIndex(boxid, index, true, function (data) {
                Box().findByBoxId(boxid, function (box) {
                    var list = box.data;
                    res.render("box/box_doors", {
                        "boxid": boxid,
                        "doordatas": list,
                        "limit": box.boxlimit
                    });
                });
                new Sim().findSimById(boxid, function (datas) {
                    var sim = datas.sim;
                    //client = mqtt.createClient(1883, '114.215.137.61');
                    mqttclient.publish(sim, 'open' + index);
                    //client.end;
                });
                new Log({
                    box_id: boxid,
                    user: req.session.user.user, //操作人
                    date: new Date(), //操作日期
                    operation: "打开箱子门:" + index + "号", //操作内容
                    opertype: "open"
                }).save();
            });
        }
    },
    boxlimit: function (req, res) {
        var flag = req.query.limit == 'true' ? true : false;

        new Box().updateColumn({box_id: req.query.box_id}, {limit: flag}, function (err) {
            res.redirect('/box/doors?boxid=' + req.query.box_id + '&&index=0')
        });
    },
    to_probality_set: function (req, res) {
        var boxid = req.query.boxid;
        Box.findOne({'box_id': boxid}).then(function (box) {
            res.render('box/box_probality_set', {
                boxid: boxid,
                box: box
            });
        }).error(function (err) {
            res.send({success: false, err: err});
        });
    },
    do_probality_set: function (req, res) {
        var newTimeArr = req.body.newTimeArr;
        var box_id = req.body.boxid;
        var probability = req.body.probability;
        var probability1 = req.body.probability1;
        console.log('~~~~~~~~~~~');
        var alarms = null;
        if (newTimeArr) {
            alarms = {happy_times: newTimeArr, probability: Number(probability), probability1: Number(probability1)};
        } else {
            alarms = {probability1: Number(probability1)};
        }
        new Box().updateColumn({box_id: box_id}, alarms, function (err) {
            var isadmin = false;
            if (req.session.user.user == 'admin') {
                isadmin = true;
            }


            if (err) {
                res.send({msg: false, isadmin: isadmin, account: req.session.user.account});
            } else {
                new Sim().findSimById(box_id, function (data) {
                    if (newTimeArr) {
                        mqttclient.publish('tv' + data.sim, JSON.stringify({
                            type: "HappyTimes",
                            message: newTimeArr + ';' + box_id
                        }));
                    }
                    res.send({msg: true, isadmin: isadmin, account: req.session.user.account});
                });


            }
        });
    },
    to_active_create: function (req, res) {
        res.render('box/box_active_create', {boxid: req.query.boxid});
    },
    do_active_create: function (req, res) {
        var pathimg = 'public/images/box_active_img/' + req.body.boxid + '/';
        if (!fs.existsSync(pathimg)) {
            fs.mkdirSync(pathimg);
        }
        fs.renameSync(req.files.inputfile.path, pathimg + req.files.inputfile.name);
        var active = new Active();
        active.box_id = req.body.boxid;
        active.imgurl = '/images/box_active_img/' + req.body.boxid + '/' + req.files.inputfile.name;
        active.activename = req.body.activename;
        active.content = req.body.content;
        active.status = 0;
        active.date = new Date();
        active.saveActive(function (err) {
            return res.redirect('/box/active/list?num=1&boxid=' + req.body.boxid);
        });
        //res.render('add_active');
    },
    active_remove: function (req, res) {
        new Active().removeActiveById(req.query.id, function (err) {
            return res.redirect('/box/active/list?num=1&boxid=' + req.body.boxid);
        });
    },
    active_list: function (req, res) {

        var page = new Page(req.query.num);
        var obj = {
            page: page,
            search: {box_id: req.query.boxid}
        };
        new Active().findForPage(obj, function (err, count, pageCount, datas) {
            if (err) {
            }
            page.pageCount = pageCount;
            res.render('box/box_active_list', {
                datas: datas,
                page: page,
                boxid: req.query.boxid
            });
        })
    }
};

